package com.stand.hardcode.controller;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stand.hardcode.entity.Item;
import com.stand.hardcode.entity.StandUser;
import com.stand.hardcode.database.PMF;

@SuppressWarnings("serial")
public class ListItemsServlet extends HttpServlet {

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		//Retrieve current user (simulate login), to be removed when integrating
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query user_query = pm.newQuery(StandUser.class);
		user_query.setFilter("username == 'User1'");
		List<StandUser> user_results = (List<StandUser>) user_query.execute();
		request.getSession().setAttribute("currentUser", user_results.get(0));
		
		//Retrieve all items
		Query item_query = pm.newQuery(Item.class);
		item_query.setOrdering("title asc");
		List<Item> item_results = (List<Item>) item_query.execute();
		request.setAttribute("itemList", item_results);
		
		pm.close();
		
		try {
			request.getRequestDispatcher("listitems.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
